package com.lz.sports

import android.hardware.usb.UsbDevice
import chen.you.comm.log.AndroidLogger
import chen.you.comm.log.AppenderLogger
import chen.you.comm.log.LogUtils
import chen.you.comm.log.MultiLogger
import com.lz.comm.SP
import com.lz.library.BuildConfig
import com.lz.library.base.ApplicationInitModule
import com.lz.library.base.BaseApp
import com.lz.library.utils.FileUtils
import com.lz.sports.core.K_IS_SUPER_MANAGER
import com.lz.sports.core.v_isSuperManager
import com.lz.sports.utils.ToastUtils
import com.lz.ub.Logger
import com.lz.ub.UBCConfig
import java.io.File

class AppInitModule : ApplicationInitModule() {


    private var hasInitLog = false

    override fun onCreate(app: BaseApp) {

        UBCConfig.init(!SP.getBoolean(K_IS_SUPER_MANAGER, v_isSuperManager), app)
        UBCConfig.addUsbStateCallback(object : UBCConfig.UsbStateCallback {
            override fun onPermission(usbDevice: UsbDevice, state: Int) {
                if (state == UBCConfig.DEVICE_PERMISSION_REFUSE) {
                    ToastUtils.showMyToast(R.string.usbPermissionFailed)
                }
            }

            override fun onEmpty() {
                ToastUtils.showMyToast(R.string.insertUsbFirst)
            }
        })


        if (hasInitLog) return
        val bufferPath: String = File(FileUtils.getCacheDir(), if (BuildConfig.isRelease) "lzsports.mmapf" else "lzsports_debug.mmapf").absolutePath
        val logfileDir: String = FileUtils.getCacheDir().absolutePath + File.separator
        val appenderLogger: AppenderLogger = AppenderLogger.Builder(logfileDir, bufferPath)
            .setDebug(true)
            .setFlushDelay(60)
            .build()
//        测试亦可用此方式
        //        测试亦可用此方式
        val multiLogger = MultiLogger()
        multiLogger.addLogger(appenderLogger)
        multiLogger.addLogger(AndroidLogger)
        LogUtils.initLogger(multiLogger)
        LogUtils.flush()
        hasInitLog = true


        Logger.printer = object : Logger.Printer {

            override fun v(tag: String, log: String) {
                LogUtils.v(tag, log)
            }

            override fun d(tag: String, log: String) {
                LogUtils.d(tag, log)
            }

            override fun i(tag: String, log: String) {
                LogUtils.i(tag, log)
            }

            override fun e(tag: String, log: String) {
                LogUtils.e(tag, log)
            }

        }
    }

}